<template>
  <div class="basetable" element-loading-text="拼命加载中">
    <!-- v-loading 设置加载 -->
    <div class="selectMenu">
      <el-button size="small" type="primary" @click="deriveClick">导出</el-button>
        <span class="spansearch">班级名称</span>
        <el-input size="small" placeholder="班级名称搜索" style="width:350px;margin-left: 16px;" @input="searchClickname"
        clearable
        v-model="inputname"
      >
      </el-input>
        
    </div>
    <div class="tableMain">
      <el-table
        :data="userList.slice((currentPage-1)*pagesize,currentPage*pagesize)"
        style="width: 100%"
        ref="table"
      >
        <el-table-column type="index" width="50" label="序号" fixed></el-table-column>
        <el-table-column prop="name" label="班级名称" width="100"></el-table-column>
        <el-table-column prop="nums" label="班级人数" width="100"></el-table-column>
        <el-table-column prop="start_time" label="开班时间" width="120"></el-table-column>
        <el-table-column prop="end_time" label="结束时间" width="120"></el-table-column>
        <el-table-column label="费用情况" width="200">
          <template slot-scope="scope">
            <p>总费用：{{scope.row.money*scope.row.nums}}元</p>
            <p>已交费用：{{Number(scope.row.money*scope.row.nums) - Number(scope.row.lost_money) }}</p>
            <p>剩余应交：{{scope.row.lost_money}}元</p>
          </template>
        </el-table-column>
        <el-table-column label="班级状态" width="180">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status == 0">未结班</el-tag>
            <el-tag v-if="scope.row.status == -1" type="danger">已结班</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="btbz" label="补贴标准" width="180"></el-table-column>
        <el-table-column prop="area" label="地区" width="180"></el-table-column>
        <el-table-column prop="bzr_tel" label="班主任联系电话" width="180"></el-table-column>
        <el-table-column prop="total_day" label="总培训时间" width="180">
          <template slot-scope="scope">
            <p>{{scope.row.total_day}}天</p>
          </template>
        </el-table-column>
        <el-table-column prop="ks_time" label="考试时间" width="180"></el-table-column>
        <el-table-column prop="sk_time_1" label="上午授课时间" width="180"></el-table-column>
        <el-table-column prop="sk_time_2" label="下午授课时间" width="180"></el-table-column>
        <el-table-column prop="sk_time_3" label="晚上授课时间" width="180"></el-table-column>
        <el-table-column prop="skdd" label="授课点" width="180"></el-table-column>
        <el-table-column prop="fzr_tel" label="授课点负责人电话" width="180"></el-table-column>
        <el-table-column fixed="right" width="320" label="操作">
          <template slot-scope="scope">
            <!-- 操作 -->
            <el-button
              ref="btn1"
              size="small"
              :disabled="scope.row.status == 0 ? false:true"
              type="primary"
              @click="whetherMoney(scope.row)"
            >费用结算</el-button>
            <el-button
              ref="btn1"
              size="small"
              :disabled="scope.row.status == 0 ? false:true"
              type="warning"
              @click="lookClass(scope.row)"
            >查看</el-button>
            <el-button
              size="small"
              type="danger"
              :disabled="scope.row.status == 0 ? false:true"
              @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button>
            <el-button
              ref="btn1"
              size="small"
              :disabled="scope.row.status == 0 ? false:true"
              type="danger"
              @click="getname(scope.row)"
            >{{scope.row.status == 0?'结班':'已结班'}}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 查看班级 -->
    <el-dialog title="班级信息" :visible.sync="dialogVisibleaLock" width="850px">
      <el-form :model="form">
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item style="margin-bottom:20px;" label="班级名称" :label-width="formLabelWidth">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
        </el-col>
          <el-col :span="10">
            <el-form-item style="margin-bottom:20px;width:80px;" label="时间" :label-width="formLabelWidth">
          <el-date-picker
            v-model="form.time"
            type="daterange"
            unlink-panels
            value-format="yyyyMMdd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item style="margin-bottom:20px;" label="费用情况" :label-width="formLabelWidth">
              <el-input v-model="form.money"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item style="margin-bottom:20px;" label="班级人数" :label-width="formLabelWidth">
              <el-input v-model="form.nums" type="number" placeholder="请输入数字"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item style="margin-bottom:20px;" label="补贴标准" :label-width="formLabelWidth">
              <el-input v-model="form.btbz"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item style="margin-bottom:20px;" label="班主任电话" :label-width="formLabelWidth">
              <el-input v-model="form.bzr_tel"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item style="margin-bottom:20px;" label="总培训时间" :label-width="formLabelWidth">
              <el-input v-model="form.total_day"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item style="margin-bottom:20px;" label="考试时间" :label-width="formLabelWidth">
              <el-input v-model="form.ks_time"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item style="margin-bottom:20px;" label="上午授课时间" :label-width="formLabelWidth">
              <el-input v-model="form.sk_time_1"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item style="margin-bottom:20px;" label="下午授课时间" :label-width="formLabelWidth">
              <el-input v-model="form.sk_time_2"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item style="margin-bottom:20px;" label="晚上授课时间" :label-width="formLabelWidth">
              <el-input v-model="form.sk_time_3"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item style="margin-bottom:20px;" label="授课地点" :label-width="formLabelWidth">
              <el-input v-model="form.skdd"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item style="margin-bottom:20px;" label="负责人电话" :label-width="formLabelWidth">
              <el-input v-model="form.fzr_tel"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item class="inputedit" label="班级状态">
              <el-radio v-model="radio3" label="0" @change="getValue()"
                >未结班</el-radio>
              <el-radio v-model="radio3" label="-1" @change="getValue()"
                >已结班</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
        
      </el-form>
    </el-dialog>
    <!-- 费用计算 -->
    <el-dialog title="费用结算" width="700px" :visible.sync="dialogWhetherMoney" @close='closeDialog'>
      <div>
        <el-form label-width="100px">
          <el-form-item label="结算部分学费" style="margin-bottom: 20px;">
            <el-input style="width: 40%; margin-right: 40px;" v-model="inputMoney" placeholder="请输入未结清费用"></el-input>
            <el-button type="warning" style="margin-right:10px;" @click="lostMoney(0)">提交费用</el-button>
          </el-form-item>
        <el-form-item label="结清学费">
          <el-button type="primary"  :disabled='settle' @click="lostMoney(1)">结清学费</el-button> 
        </el-form-item>
        </el-form>      
      </div>
    </el-dialog>
    <!-- 导出 -->
    <!--  -->
    <el-dialog
      title="导出片段"
      :visible.sync="dialogVisibletwo"
      width="45%"
      :before-close="handleClose"
    >
      <div>
        <div style="margin: 15px 0;"></div>
        <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
          <el-checkbox v-for="(item,v) in cities" :label="item" :key="v">{{item.name}}</el-checkbox>
        </el-checkbox-group>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibletwo = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisibleClick">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加课程 -->
    <el-dialog title="添加课程" :visible.sync="dialogFormVisibleb">
      <Classs></Classs>
    </el-dialog>
    <!-- 分配教师 -->
    <el-dialog title="添加教师" width="600px" :visible.sync="dialogFormVisiblebac">
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="教师名称">
          <el-input v-model="form.date" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleaLock = false">取 消</el-button>
        <el-button type="primary" @click="lookClassClick">确 定</el-button>
      </div>
    </el-dialog>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 25, 50,100]"
      :page-size="pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="userList.length"
    ></el-pagination>
  </div>
</template>

<script>
import axios from "axios";
import Export from "./export";
import Classs from "../../components/classsss";
import baseUrl from "../../config/index"
const cityOptions = [
  "班级名称",
  "班级人数",
  "合格人数",
  "开班时间",
  "结束时间",
  "结班时间",
  "费用情况",
  "班级状态",
  "班级状态",
  "班级状态",
  "班级状态",
];
export default {
  components: {
    Export,
    Classs
  },
  data() {
    return {
      tablelsistData:[],
      currentPage: 1, //初始页
      pagesize: 10, //    每页的数据
      userList: [],
      tableData: [], //   表格的数据
      radio1: "未结班",
      cities: [
        { name: "班级名称", id: "name" },
        { name: "班级人数", id: "nums" },
        { name: "开班时间", id: "start_time" },
        { name: "结班时间", id: "end_time" },
        { name: "总费用", id: "money" },
        { name: "未交费用", id: "lost_money" },
        { name: "班级状态", id: "status" },
        { name: "补贴标准", id: "btbz" },
        { name: "地区", id: "area" },
        { name: "班主任联系电话", id: "bzr_tel" },
        { name: "总培训时间", id: "total_day" },
        { name: "考试时间", id: "ks_time" },
        { name: "上午授课时间", id: "sk_time_1" },
        { name: "下午授课时间", id: "sk_time_2" },
        { name: "晚午授课时间", id: "sk_time_3" },
        { name: "授课点", id: "skdd" },
        { name: "授课点负责人电话", id: "fzr_tel" },
      ],
      options: [],
      radio3:'',
      value: "",
      dialogFormVisiblea: false,
      dialogFormVisibleb: false,
      dialogFormVisiblebac: false,
      dialogVisibletwo: false,
      formLabelWidth: "100px",
      isIndeterminate: true,
      checkAll: false,
      checkedCities: [
        {name:"班级名称" , id:'status'},
        "班级人数",
        "合格人数",
        "开班时间",
        "结班时间",
        "费用情况",
        "班级状态"
      ],
      arr1:[],
      arr2:[],
      // 设置form用于进行添加的时候绑定值
      form: {
        name: "",
        time: "",
        money: "",
        nums: "",
        id: "" //编辑ID
      },
      currentIndex: "",
      cut: 1, // 编辑添加切换
      dialogVisibleaLock: false, //查看班级弹窗
      ValueMoney: "", //剩余未结清
      dialogWhetherMoney: false, //费用结算
      inputMoney: "",
      lostMoneyObj: {},
      tableHeight: window.innerHeight - 200, //表格高度
      inputname: "", //搜索值班级名称
      inputstart_time: "", //搜索值开班时间
      settle:false,
    };
  },
  created() {},
  mounted() {
    this.getClassList(); //班级列表
  },
  methods: {
    closeDialog(){
      this.inputMoney = "";
    },
    // 初始页currentPage、初始每页数据数pagesize和数据data
    handleSizeChange: function(size) {
      this.pagesize = size;
    },
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage;
    },
    // 导出
    deriveClick() {
      this.dialogVisibletwo = true;
    },
    // 导出字段
    handleCheckAllChange(val) {
      this.checkedCities = val ? this.cities : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      this.arr1 = value.map(item=>item.name).slice(7)
      this.arr2 = value.map(item=>item.id).slice(7) 
      let a = JSON.parse(JSON.stringify(this.arr1))
      let b = JSON.parse(JSON.stringify(this.arr2))
      console.log("a",a);
      console.log("b",b);
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cities.length;
    },
    // 确定导出
    dialogVisibleClick() {
      this.dialogVisibletwo = false;
      this.export2Excel();
    },
    // 导出
    export2Excel() {
      require.ensure([], () => {
        let a = JSON.parse(JSON.stringify(this.arr1))
        let b = JSON.parse(JSON.stringify(this.arr2))
        const { export_json_to_excel } = require("../../excal/Export2Excel");
        const tHeader = a; // 上面设置Excel的表格第一行的标题
        const filterVal = b; // 上面的index、phone_Num、school_Name是tableData里对象的属性
        const list = this.userList; //把data里的tableData存到list
        const data = this.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, "班级列表");
      });
    },
    handleClose(done) {
      done();
    },
    formatJson(filterVal, jsonData) {
      console.log(filterVal);
      console.log(jsonData);
      for(var i=0;i<jsonData.length;i++){
        jsonData[i].status === -1?jsonData[i].status = '已结班': jsonData[i].status = '未结班'
      }
      return jsonData.map(v => filterVal.map(j => v[j]));
    },
    addteacher() {
      this.dialogFormVisiblebac = true;
    },
    relieve() {},
    exporta() {},
    // Import() {
    //   this.dialogFormVisiblea = true;
    // },
    //获取班级列表
    async getClassList() {
      var _this = this;
      this.userList = (await this.$api.home.classList()).data.data;
      this.userList.forEach(e => {
        let str = e.start_time.toString();
        str = this.insertStr(str, 4, "-");
        str = this.insertStr(str, 7, "-");
        let str1 = e.end_time.toString();
        str1 = this.insertStr(str1, 4, "-");
        str1 = this.insertStr(str1, 7, "-");
        e.end_time = str1;
        e.start_time = str;
      });
    },
    insertStr(soure, start, newStr) {
      return soure.slice(0, start) + newStr + soure.slice(start);
    },
    // 导入
    update() {
      this.tableData.push(this.form);
      this.dialogFormVisiblea = false;
    },
    // 查看班级
    async lookClass(val) {
      let classlists = (await this.$api.home.courseShow({
        id:val.id
      })).data.data
      console.log(val);
      this.radio3 = JSON.stringify(val.status)
      console.log();
      this.tablelsistData = classlists
      this.dialogVisibleaLock = true;
      let time = [];
      val.start_time = val.start_time.toString().split("-").join("");
      val.end_time = val.end_time.toString().split("-").join("");
      time.push(val.start_time.toString(), val.end_time.toString());
      this.form = {
        name: val.name,
        money: val.money,
        nums: val.nums,
        time: time,
        id: val.id,
        btbz:val.btbz,
        area:val.area,
        bzr_tel:val.bzr_tel,
        fzr_tel:val.fzr_tel,
        sk_time_1:val.sk_time_1,
        sk_time_2:val.sk_time_2,
        sk_time_3:val.sk_time_3,
        skdd:val.skdd,
        total_day:val.total_day,
        ks_time:val.ks_time,
        
      };
    },
    lookClassClick() {
      this.dialogVisibleaLock = false;
    },
    handleEdit(index, row) {
      // 将数据的index传递过来用于实现数据的回显
      this.form = this.tableData[index];
      this.currentIndex = index;
      // 设置对话框的可见
      this.dialogFormVisible = true;
    },
    //结班操作
     getname(val) {
      this.$confirm('确定要结班吗, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const params = {
            id: val.id
          };
          let lockForm = await this.$api.home.lockClass(params);
            if(lockForm.data.code == 200){
                this.$message({
                type: 'success',
                message: lockForm.data.msg
            });    
            this.getClassList();
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消结班'
          });          
        });
    },
    //删除班级
    handleDelete(index, row) {
      let a = localStorage.getItem('name').replace(/\"/g,"")
      if(a == '超级管理员'){
        this.$confirm("永久删除该班级, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          let params = {
            id: row.id
          };
          let del = await this.$api.home.delClass(params);
          if (del.data.code == 200) {
            this.getClassList();
            this.$message({
              type: "success",
              message: "删除成功!"
            });
          } else {
            this.$message.error(del.data.msg);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
      }else{
        this.$message({
              message: "只有超级管理员可以删除班级信息",
              type: "error"
            });
      }
      // 设置类似于console类型的功能
      
    },
    //费用计算
    whetherMoney(val) {
      this.dialogWhetherMoney = true;
      this.lostMoneyObj = val;
      this.inputMoney = "";
      if(val.lost_money == 0.00){
        this.settle = true
      }else{
        this.settle = false
      }
    },
    async lostMoney(v) {
      let url = baseUrl.DevUrl
      let token = localStorage.getItem('token').replace("\"", "");
      if (v == 0) {
        let num =
          Number(this.lostMoneyObj.money * this.lostMoneyObj.nums) -
          Number(this.lostMoneyObj.lost_money);
        if (this.inputMoney > num) {
          this.$message({
            message: "金额超出",
            type: "warning"
          });
          return false;
        }
         axios({
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'token':token
            },
            method: 'post',
            type:'JSON',
            url:url +".datum/money_to_clear",
            params: {
              id: this.lostMoneyObj.id,
              is_end: "",
              lost_money: this.inputMoney
            }
          })
          .then(res => {
            if (res.data.code == 200) {
              this.$message({
                type: "success",
                message: res.data.msg
              });
              this.getClassList();
              this.dialogWhetherMoney = false;
            } else {
              this.$message.error(res.data.msg);
            }
          });
      } else {
         this.$confirm('结清费用，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
         axios({
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'token':token
            },
            method: 'post',
            type:'JSON',
            url:url +".datum/money_to_clear",
            params: {
              id: this.lostMoneyObj.id,
              is_end: 1,
              lost_money: ""
            }
          })
          .then(res => {
            if (res.data.code == 200) {
              this.$message({
                type: "success",
                message: res.data.msg
              });
              this.getClassList();
              this.dialogWhetherMoney = false;
            } else {
              this.$message.error(res.data.msg);
            }
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });    
        });
      }
    },
    //搜索班级名称
    searchClickname() {
      let searchText = this.inputname;
      let list = [];
      if (searchText) {
        list = this.userList.filter(e => {
          return e.name.match(searchText);
        });
        this.userList = list;
      } else {
        this.getClassList();
      }
    },
  }
};
</script>
<style lang="less" scope>
.tableMain {
  margin-top: 10px;
}
//搜索框文字
 .spansearch{
   color: #409EFF;
   font-size: 15px;
   margin-left: 20px;
 }
.page {
  float: left;
  margin-top: 10px;
}

.lost_money {
  display: flex;
}
.residue {
  display: flex;

  .el-input__inner {
    width: 20%;
  }
}

.el-input--suffix {
  .el-input-group__append {
    border-color: #1890ff;
    .btnSearch {
      background: #1890ff;
      color: #fff;
      border-radius: 0;
    }
  }
}
</style>